﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using LaunchMeNot.Core;
using Lime49.UI;
using Lime49.WPF;
using Microsoft.Windows.Controls;

namespace LaunchMeNot
{
    /// <summary>
    /// Displays windows managed startup entries in a grouped datagrid.
    /// </summary>
    public partial class StartupEntryDataGrid : UserControl
    {
        private List<IStartupEntry> _entries; // cached copy of displayed strongly typed entries or null.

        /// <summary>
        /// Gets the selected entry.
        /// </summary>
        /// <value>The selected entry.</value>
        public IStartupEntry SelectedEntry
        {
            get { return dgEntries.SelectedItem as IStartupEntry; }
        }
        public System.Collections.IList SelectedEntries
        {
            get { return dgEntries.SelectedItems; }
        }

        /// <summary>
        /// Gets a cached collection of displayed startup entries.
        /// </summary>
        /// <value>A cached collection of startup entries, or <c>null</c> if Refresh has not yet been executed.</value>
        public List<IStartupEntry> StartupEntries
        {
            get { return _entries; }
        }

        public List<IStartupEntry> Items
        {
            get { return _entries; }
        }

        public StartupEntryDataGrid()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Refreshes the list of entries.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="System.Windows.Input.ExecutedRoutedEventArgs"/> instance containing the event data.</param>
        private void RefreshEntries(object sender, ExecutedRoutedEventArgs e) {
            BackgroundWorker worker = new BackgroundWorker();
            worker.DoWork += (s, dwe) => {
                 dwe.Result = LaunchMeNotBLL.GetEntries(StartupEntryType.AllUsersStartup | StartupEntryType.CurrentUserRun | StartupEntryType.CurrentUserStartup | StartupEntryType.LocalMachineRun);
             };
            worker.RunWorkerCompleted += (s, rwe) =>
            {
                dgEntries.IsEnabled = true;
                if (rwe.Error != null) {
                    DialogBox.ShowAlert(Window.GetWindow(this), rwe.Error.Message, I18nUtils.GetString("Errors", "ErrorLoadingEntries"));
                } else if (rwe.Result is IEnumerable<IStartupEntry>) {
                    _entries = ((IEnumerable<IStartupEntry>)rwe.Result).ToList();
                    var entrySource = (CollectionViewSource)this.FindResource("EntrySource");
                    entrySource.Source = _entries;
                }
            };
            worker.RunWorkerAsync();
            dgEntries.IsEnabled = false;
            CommandManager.InvalidateRequerySuggested();
        }

        #region Datagrid Specific
        /// <summary>
        /// Allows editing on double click.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Input.MouseButtonEventArgs"/> instance containing the event data.</param>
        private void dgCell_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            var cell = sender as DataGridCell;
            if (cell == null)
                return;
            ApplicationCommands.Properties.Execute(cell.DataContext, this);
        }

        /// <summary>
        /// Allows deletion when pressing the Delete key.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Input.KeyEventArgs"/> instance containing the event data.</param>
        private void dgEntries_PreviewKeyDown(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Delete) {
                List<IStartupEntry> selectedEntries = new List<IStartupEntry>();
                foreach (var item in dgEntries.SelectedItems) {
                    if (item is IStartupEntry)
                        selectedEntries.Add((IStartupEntry)item);
                }
                ApplicationCommands.Delete.Execute(selectedEntries, this);
                //todo: impl.
                //DeleteLaunchMeNotEntries(selectedEntries);
            }
        }
        #endregion
    }
}
